package server

import (
	"errors"
	"fitness/rpc/initiate/mysql"
	"fitness/rpc/proto/user"
	"log"
)

func UserRegister(in *user.UserRegisterReq) (*user.UserRegisterResp, error) {
	m := mysql.User{
		Phone:    in.Phone,
		Password: in.Password,
	}
	err := m.Create()
	if err != nil {
		log.Println("用户注册失败")
		return nil, errors.New("用户注册失败")
	}
	return &user.UserRegisterResp{
		Greet: "用户注册成功",
		Code:  200,
	}, nil
}

func UserLogin(in *user.UserLoginReq) (*user.UserLoginResp, error) {
	m := mysql.User{
		Phone:    in.Phone,
		Password: in.Password,
	}
	if m.ID == 0 {
		log.Println("该用户未注册")
		err := m.Create()
		if err != nil {
			log.Println("用户注册")
			return nil, errors.New("用户注册失败")
		}
	}
	err := m.Find(in.Phone)
	if err != nil {
		log.Println("未查询到该用户")
		return nil, errors.New("未查询到该用户")
	}

	if err != nil {
		log.Println("用户注册")
		return nil, errors.New("用户注册失败")
	}
	return &user.UserLoginResp{
		Greet: "用户登陆成功",
		Code:  200,
	}, nil
}

func FitnessCreate(in *user.FitnessCreateReq) (*user.FitnessCreateResp, error) {
	f := mysql.Fitness{
		Title:       in.Title,
		Duration:    in.Duration,
		Author:      in.String_,
		Kilocalorie: in.Kilocalorie,
		Browse:      in.Browse,
	}
	err := f.Create()
	if err != nil {
		log.Println("添加失败")
		return nil, errors.New("添加失败")
	}
	return &user.FitnessCreateResp{
		Greet: "添加成功",
		Code:  200,
	}, nil
}

func FitnessList(in *user.FitnessListReq) (*user.FitnessListResp, error) {
	f := mysql.Fitness{}
	li, err := f.List()
	if err != nil {
		log.Println("全部展示失败")
		return nil, errors.New("全部展示失败")
	}
	list := []*user.FitnessItem{}
	for _, fit := range li {
		lists := &user.FitnessItem{
			Title:       fit.Title,
			Duration:    fit.Duration,
			String_:     fit.Author,
			Kilocalorie: fit.Kilocalorie,
		}
		list = append(list, lists)
	}
	return &user.FitnessListResp{List: list}, nil
}

func FitnessLike(in *user.FitnessLikeReq) (*user.FitnessListResp, error) {
	f := mysql.Fitness{}
	fithess, err := f.GetFithess()
	if err != nil {
		log.Println("推荐失败")
		return nil, errors.New("推荐失败")
	}
	list := []*user.FitnessItem{}
	for _, fit := range fithess {
		lists := &user.FitnessItem{
			Title:       fit.Title,
			Duration:    fit.Duration,
			String_:     fit.Title,
			Kilocalorie: fit.Kilocalorie,
			Id:          int64(fit.ID),
		}
		list = append(list, lists)
	}
	return &user.FitnessListResp{List: list}, nil
}
